<template>
  <div class="chart-container">
    <chart ref="chart1Ref" id="chart1" :options="chartOptions" height="360px" />
    <chart
      ref="chart2Ref"
      id="chart2"
      :options="currentChartOptions"
      height="360px"
      class="mt20"
    />
  </div>
</template>

<script setup>
/**
 * 故障波形图表展示组件
 * 包含两个图表：
 * 1. 主图表：显示A、B、C相电压和零线电压的波形
 * 2. 电流图表：单独显示故障点位传感器电流波形
 */

import { useDark } from "@vueuse/core";
const isDarkMode = useDark();
import chart from "@/components/chart";
import { min } from "lodash-es";
const route = useRoute();
const { proxy } = getCurrentInstance();

// 显示加载提示
proxy.$modal.loading("正在加载...");
const id = ref(null);
// 定义图表ref变量，用于获取ECharts实例
const chart1Ref = ref(null);
const chart2Ref = ref(null);

// 存储所有图表实例的数组，用于联动控制
const chartInstances = ref([]);
const chartOptions = ref({
  title: {
    text: "",
    left: "center",
    textStyle: {
      color: "#ff0000",
      fontSize: 22,
    },
  },
  tooltip: {
    trigger: "axis",
    axisPointer: {
      type: "line",
      lineStyle: {
        color: "#FF0000",
        width: 1,
      },
      // 联动配置：连接所有图表的X轴
      link: {
        xAxisIndex: "all", // 这会让所有图表的指示线同步移动
      },
    },
    // 自定义tooltip格式化函数
    formatter: function (params) {
      // 通过dataIndex获取x轴的ms值
      const index = params[0]?.dataIndex;
      const msValue = chartOptions.value.xAxis.data[index] || "";
      let result = `时间: ${msValue}<br/>`;
      params.forEach((param) => {
        // 使用 toFixed(2) 确保结果最多两位小数
        result +=
          param.seriesName + ": " + param.value.toFixed(2) + "g(m/s²)<br/>";
      });
      return result;
    },
  },
  legend: {
    type: "scroll",
    top: "8%",
    left: "center",
    textStyle: {
      color: "#333",
    },
  },
  color: ["#FFFF00", "#0000FF", "#FF0000"],
  grid: {
    left: "3%",
    right: "4%",
    bottom: "15%", // 进一步减小底部边距，确保X轴标签可见
    containLabel: true,
  },
  xAxis: {
    type: "category",
    name: "",
    nameLocation: "start",
    boundaryGap: false,
    axisLabel: {
      interval: 64,
      showMaxLabel: true,
    },
  },
  yAxis: {
    type: "value",
    name: "加速度(g(m/s²))",
    splitLine: {
      lineStyle: {
        type: "dashed",
        color: "#666666",
      },
    },
    axisLabel: {
      formatter: "{value}",
    },
  },
  dataZoom: [
    {
      type: "inside",
      start: 0,
      end: 100,
      zoomLock: false, // 允许缩放以查看特定时间段
      moveOnMouseMove: true,
      moveOnMouseWheel: true,
    },
    {
      start: 0,
      end: 100,
      xAxisIndex: 0,
      handleIcon:
        "M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z",
      handleStyle: {
        color: "#fff",
        shadowBlur: 3,
        shadowColor: "rgba(0, 0, 0, 0.6)",
        shadowOffsetX: 2,
        shadowOffsetY: 2,
      },
    },
  ],
  series: [],
});

/**
 * 电流图表配置2
 */
const currentChartOptions = ref({
  title: {
    text: "",
    left: "center",
    textStyle: {
      color: "#ff0000",
      fontSize: 22,
    },
  },
  tooltip: {
    trigger: "axis",
    axisPointer: {
      type: "line",
      lineStyle: {
        color: "#FF0000",
        width: 1,
      },
      // 联动配置：连接所有图表的X轴
      link: {
        xAxisIndex: "all", // 这会让所有图表的指示线同步移动
      },
    },
    // 自定义tooltip格式化函数
    formatter: function (params) {
      const index = params[0]?.dataIndex;
      const hzValue = currentChartOptions.value.xAxis.data[index] || '';
      let result = `频率: ${hzValue}<br/>`;
      params.forEach(param => {
          // 使用 toFixed(2) 确保结果最多两位小数
          result += param.seriesName + ': ' + param.value.toFixed(2) + 'g(m/s²)<br/>';
      });
      return result;
    },
  },
  legend: {
    type: "scroll",
    top: "8%",
    left: "center",
    textStyle: {
      color: "#333",
    },
  },
  color: ["#FFFF00", "#0000FF", "#FF0000"],
  grid: {
    left: "3%",
    right: "4%",
    bottom: "15%", // 进一步减小底部边距，确保X轴标签可见
    containLabel: true,
  },
  xAxis: {
    type: "category",
    name: "",
    nameLocation: "start",
    boundaryGap: false,
    axisLabel: {
        interval: 29, // 每32个点显示一个标签，避免重叠
        showMaxLabel: true
      },
  },
  yAxis: {
    type: "value",
    name: "频谱(g(m/s²))",
    splitLine: {
      lineStyle: {
        type: "dashed",
        color: "#666666",
      },
    },
    axisLabel: {
      formatter: "{value}",
    },
  },
   dataZoom: [
    {
      type: "inside",
      start: 0,
      end: 100,
      zoomLock: false, // 允许缩放以查看特定时间段
      moveOnMouseMove: true,
      moveOnMouseWheel: true,
    },
    {
      start: 0,
      end: 100,
      xAxisIndex: 0,
      handleIcon:
        "M10.7,11.9v-1.3H9.3v1.3c-4.9,0.3-8.8,4.4-8.8,9.4c0,5,3.9,9.1,8.8,9.4v1.3h1.3v-1.3c4.9-0.3,8.8-4.4,8.8-9.4C19.5,16.3,15.6,12.2,10.7,11.9z M13.3,24.4H6.7V23h6.6V24.4z M13.3,19.6H6.7v-1.4h6.6V19.6z",
      handleStyle: {
        color: "#fff",
        shadowBlur: 3,
        shadowColor: "rgba(0, 0, 0, 0.6)",
        shadowOffsetX: 2,
        shadowOffsetY: 2,
      },
    },
  ],
  series: [],
});
// 监听主题变化
watch(
  isDarkMode,
  (newIsDarkMode) => {
    const textColor = newIsDarkMode ? "#fff" : "#333";
    // 更新主图表文字颜色
    // chartOptions.value.title.textStyle.color = textColor;
    chartOptions.value.legend.textStyle.color = textColor;
    chartOptions.value.xAxis.axisLabel.textStyle = {
      color: textColor,
      fontSize: 12,
    };
    chartOptions.value.yAxis.axisLabel.textStyle = { color: textColor };
    // 更新电流图表文字颜色
    currentChartOptions.value.title.textStyle.color = textColor;
    currentChartOptions.value.legend.textStyle.color = textColor;
    currentChartOptions.value.xAxis.axisLabel.textStyle = { color: textColor };
    currentChartOptions.value.yAxis.axisLabel.textStyle = { color: textColor };
  },
  { immediate: true }
);

// 组件挂载时初始化图表数据
onMounted(() => {
  // 添加 passive 事件监听器配置
  const chartContainer = document.querySelector(".chart-container");
  if (chartContainer) {
    chartContainer.addEventListener("mousewheel", () => {}, { passive: true });
  }
  id.value = route.query.id;
  const { dev_Name, dev_id, alarmtime } = route.query;
  proxy.cloudTv_API
    .GetOneWaveInfo({ id: id.value })
    .then((res) => {
      const data = {
        series: [
          { name: "X轴加速度值", data: res.data.x_Axis },
          { name: "Y轴加速度值", data: res.data.y_Axis },
          { name: "Z轴加速度值", data: res.data.z_Axis },
        ],
      };
      const dataLength = 1024;
      const totalTime = 200; // 总时间(ms)
      const timePerPoint = totalTime / dataLength; // 每个点对应的时间
      const xAxisData = new Array(dataLength).fill("");
      // 为每个数据点生成精确时间标签
      for (let index = 0; index < dataLength; index++) {
        const time = index * timePerPoint;
        // 保留两位小数并格式化时间标签
        xAxisData[index] = `${time.toFixed(2)}ms`;
      }
      // 确保最后一个点显示200ms
      xAxisData[dataLength - 1] = "200ms";
      chartOptions.value.title.text = `${res.data.device_ID} — ${res.data.sns_Timestamp}`;
      chartOptions.value.xAxis.data = xAxisData;
      chartOptions.value.series = data.series.map((item) => ({
        name: item.name,
        type: "line",
        smooth: false,
        symbol: "circle",
        symbolSize: 0,
        data: item.data,
        itemStyle: {
          normal: {
            lineStyle: {
              width: 1,
            },
          },
        },
      }));

      const data2 = {
        series: [
          { name: "X轴频谱", data: res.data.x_PU },
          { name: "Y轴频谱", data: res.data.y_PU },
          { name: "Z轴频谱", data: res.data.z_PU },
        ],
      };
      const dataLength2 = 512;
      const totalFrequency = 2560; // 总频率范围
      const frequencyPerPoint = totalFrequency / (dataLength2 - 1); // 使用间隔数计算频率步长
      const xAxisData2 = new Array(dataLength2).fill("");
      // 循环为每个数据点生成精确频率标签
      for (let index = 0; index < dataLength2; index++) {
        const frequency = index * frequencyPerPoint;
        // 保留两位小数并格式化频率标签
        xAxisData2[index] = `${frequency.toFixed(2)}Hz`;
      }
      // 更新 xAxis 数据
      currentChartOptions.value.xAxis.data = xAxisData2;
      // 更新主图表2
      currentChartOptions.value.series = data2.series.map((item) => ({
        name: item.name,
        type: "line",
        smooth: false,
        symbol: "circle",
        symbolSize: 0,
        data: item.data,
        itemStyle: {
          normal: {
            lineStyle: {
              width: 1,
            },
          },
        },
      }));
      console.log(currentChartOptions.value);
      // // 数据加载完成后，初始化图表联动功能
      // initializeChartLinkage();
    })
    .finally(() => {
      proxy.$modal.closeLoading();
    });
});
</script>

<style lang="scss" scoped>
.chart-container {
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  height: calc(100vh - 84px);
  overflow-y: auto;

  .mt20 {
    margin-top: 20px;
  }

  // 普通主题文字颜色
  color: #333;

  &.dark-mode {
    // 暗黑主题文字颜色
    color: white;
  }
}

// 图表标题、图例等文字颜色
.chart-container .chart-title,
.chart-container .legend-text {
  color: inherit;
}
</style>